package com.william.jdbcplus.core.ds;

import com.alibaba.druid.pool.DruidDataSource;
import com.william.jdbcplus.core.util.JdbcUtil;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 动态数据源
 *
 * @author william
 */
public class DynamicDataSource extends AbstractRoutingDataSource {

    @Override
    protected String determineCurrentLookupKey() {
        return DataSourceContextHolder.get();
    }

    public boolean isDefaultDatabase() {
        DataSource dataSource = determineTargetDataSource();
        if (this.getDefaultTargetDataSource() == dataSource) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取指定数据源
     *
     * @param code
     * @return
     */
    public DruidDataSource getDsByCode(String code) {
        Map<String, DruidDataSource> targetDsMap = this.getTargetDataSources();
        if (targetDsMap.containsKey(code)) {
            return targetDsMap.get(code);
        }

        return null;
    }

    /**
     * 重新载入目标数据源
     *
     * @param configList
     */
    public void reloadTargetDataSources(List<DatasourceConfig> configList) {
        Map<String, DruidDataSource> targetDsMap = this.getTargetDataSources();
        Map<String, DruidDataSource> newTargetDataSources = new HashMap<>();
        for (DatasourceConfig config : configList) {
            if (targetDsMap.containsKey(config.getLookup())) {
                DruidDataSource ds = targetDsMap.get(config.getLookup());
                String url = ds.getUrl();
                String username = ds.getUsername();
                String password = ds.getPassword();

                //全部连接相同，不需要创建数据源， 直接从内存中获取数据源
                if (url.equals(config.getUrl()) && username.equals(config.getUsername()) && password.equals(config.getPassword())) {
                    newTargetDataSources.put(config.getLookup(), ds);
                } else {
                    DruidDataSource dataSource = JdbcUtil.createDataSource(config.getUrl(), config.getUsername(), config.getPassword());
                    newTargetDataSources.put(config.getLookup(), dataSource);
                }
            } else {
                DruidDataSource dataSource = JdbcUtil.createDataSource(config.getUrl(), config.getUsername(), config.getPassword());
                newTargetDataSources.put(config.getLookup(), dataSource);
            }
        }

        this.setTargetDataSources(newTargetDataSources);
        this.afterPropertiesSet();
    }
}